import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus';
import { getCookie } from '../utils';
import router from '../router';
import { Data } from '../types';

//增加请求接口时登录和未登录的处理逻辑
const request = axios.create({
  baseURL: import.meta.env.MODE !== 'production' ? '/api' : '',
});

//拦截器
request.interceptors.request.use((config: AxiosRequestConfig) => {
  //django SessionAuthentication need csrf token
  if (config.headers) config.headers['X-CSRFToken'] = getCookie('csrftoken');
  return config;
});

request.interceptors.response.use(
  (response: AxiosResponse<Data>) => {
    const data = response.data;
    console.log('response :>> ', response);
    if (data.status === '401') {
      localStorage.removeItem('user');
      ElMessage({
        message: data.error || data.status,
        type: 'error',
        duration: 1.5 * 1000,
      });
    }
    if (data.success === false && data.msg) {
      ElMessage({
        message: data.msg,
        type: 'error',
        duration: 1.5 * 1000,
      });
    }
    return data;
  },
  ({ message, response }) => {
    console.log('err :>> ', message, response);
    if (response && response.data && response.data.detail) {
      ElMessage({
        message: response.data.detail,
        type: 'error',
        duration: 2 * 1000,
      });
    } else {
      ElMessage({
        message: message,
        type: 'error',
        duration: 2 * 1000,
      });
    }
    if(response&&(response.status===401||response.status===403)){
      localStorage.removeItem('user')
      return router.push('/login')
    }
    return Promise.reject(message)
  }
);
// 成功的处理回调  失败时候的处理回调
export default request;
